// pages/site/select-site/select-site.js
var httpUtil = require('../../../utils/httpUtil.js');
var uiUtil = require('../../../utils/uiUtil.js');
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
var key = "QR7BZ-UDZ3R-SS7WQ-WLPBD-76352-5YBB5";
var qqmapsdk = new QQMapWX({key: key});
const app = getApp();
var that;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userLocation: null,//用户地理位置
    siteLists:{
      totalCount: null,
      pageCount: null,
      pageNo: "0",
      pageSize: "30",
      dataList:[]
    },


    requestGoodsTask: null, //请求task
    isLoadingMore: false,
    enableLoadMore: true,

    isSearchBtn:false,
    searchLists:[]

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    that.setData({
      userLocation: app.globalData.userLocation
    });
    that.getSearchUsedAddress();
  },


  /**
   * 显示搜索
   */
  searchBtn(e){
    let value = e.detail.value;
    if(value){
      that.setData({
        isSearchBtn:true
      })
    } else {
      that.setData({
        isSearchBtn: false
      })
    }
  },

  /**
   * 搜索
   */
  searchMch: function (res, text) {
    let searchValue = text || res.detail.value.search;
    qqmapsdk.search({
      keyword: searchValue,
      address_format: 'short',
      region:"滨州市",
      page_size:20,
      success: function (res) {
        that.setData({
          searchLists: res.data
        })
      },
      fail: function (res) {
        uiUtil.showToast("查询失败");
      }
    });
  },

  /**
   * 重新定位
   */
  getNewLocation(){
    uiUtil.showLoading("请稍候..");
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      highAccuracyExpireTime: 4000,
      success(res) {
        that.location(res.latitude, res.longitude,function(e){
          var pages = getCurrentPages();
          var lastPage = pages[pages.length - 2];
          if (lastPage.route == "pages/index/navigationbar/navigationbar") {
            lastPage.setData({
              userLocation: e
            })
            lastPage.refresherrefreshHome();
          }
        });
      },
      fail(res) {
        uiUtil.hideLoading();
      }
    })
  },

  /**
   * 获取位置信息
   */
  location(lat,lng,fun){
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: lat,
        longitude: lng
      },
      get_poi: 1,
      poi_options: "policy=2;radius=100;page_size=1;page_index=1",
      success: function (res) {
        uiUtil.hideLoading();
        app.globalData.userLocation = res.result;
        that.setData({
          userLocation: res.result
        })
        
        fun(res.result);
      },
      fail: function (res) {
        uiUtil.showToast("重新定位失败");
      }
    });
  },

  /**
  * 地址选择
  */
  selectSite(e) {
    let item = e.currentTarget.dataset.item;
    that.setData({
      "userLocation.pois[0].title":item.area,
      "userLocation.pois[0].location.lat":item.lat,
      "userLocation.pois[0].location.lng":item.lng,
      "userLocation.pois[0].site":item
    })
    setTimeout(function () {
      var pages = getCurrentPages();
      var lastPage = pages[pages.length - 2];
      if (lastPage.route == "pages/index/navigationbar/navigationbar") {
        lastPage.setData({
          userLocation: that.data.userLocation
        })
        app.globalData.userLocation = that.data.userLocation;
        lastPage.refresherrefreshHome();
        wx.navigateBack({
          delta: 1,
        });
      }
    }, 300)
  },
  selectSearchSite(e){
    let item = e.currentTarget.dataset.item;
    app.globalData.userLocation.pois[0] = item;
    that.setData({
      "userLocation.pois[0]": item
    })
    setTimeout(function () {
      var pages = getCurrentPages();
      var lastPage = pages[pages.length - 2];
      if (lastPage.route == "pages/index/navigationbar/navigationbar") {
        lastPage.setData({
          "userLocation.pois[0]": item
        })
        lastPage.refresherrefreshHome();
        wx.navigateBack({
          delta: 1,
        });
      }
    }, 300)
  },

  /**
   * 常用地址查询
   */
  getSearchUsedAddress(){
    let pageNo = (parseInt(that.data.siteLists.pageNo) + 1).toString();
    let pageSize = that.data.siteLists.pageSize;
    let dataList = that.data.siteLists.dataList;
    let totalCount = that.data.siteLists.totalCount;

    var lastRequestTask = that.data.requestGoodsTask;
    if (lastRequestTask) {
      try {
        lastRequestTask.abort()
      } catch (e) { }
    }

    var curPage = that.data.siteLists.pageNo
    if (curPage != 0 && (!that.data.enableLoadMore || that.data.isLoadingMore)) { //不可加载||正在加载
      return;
    }

    var requestTask = httpUtil.PostRequest("searchUsedAddress", {
      pageNo: pageNo,
      pageSize: pageSize
    }, {
        success(res) {
          if (0 == that.data.siteLists.totalCount) {
            res.dataList = res.dataList || []
            if (res.dataList.length == 0) { //内容为空
              that.setData({
                fail: true
              })
            } 
          } else {
            res.dataList = dataList.concat(res.dataList || []);
          }
          that.setData({
            siteLists: res,
            enableLoadMore: res.dataList.length < res.totalCount,
          })
        },
        fail(code, res) {
          that.setData({
            enableLoadMore: false,
          })
          uiUtil.showToast(res);
        },
        complete() {
          that.setData({
            isLoadingMore: false
          })
        }
      })
    that.setData({
      requestGoodsTask: requestTask
    })
  },

  
  /**
  * 触底加载
  */
  onReachBottom() {
    that.getSearchUsedAddress();
  },


  /**
  * 回调刷新
  */
  onResultRegisterSuccess() {
    that.setData({
      siteLists: {
        totalCount: null,
        pageCount: null,
        pageNo: "0",
        pageSize: "30",
        dataList: []
      },
      requestGoodsTask: null, //请求task
      isLoadingMore: false,
      enableLoadMore: true
    })
    that.getSearchUsedAddress();
  }
  
})